var fs = require('fs');
var Article = require('../models/article.js');
var BookMark = require('../models/bookMark.js');
var logger = require('../config/log').logger('index');
var rssService = require('../service/blogRssService.js');
var imageService = require('../service/imageService.js');


var imageList = ['images/curator.jpg', 'images/nasa.jpg'];

/*
 * GET home page.
 */

exports.index = function(req, res) {
    logger.debug('Open index page.');
    updateImage();

    Article.createTable(function(err) {
        if (err) {
            logger.error('Open index and create table err: ' + err);
        };

        Article.fetch(function(dataset, err) {
            if (err) {
                logger.error('Open index and fetch articles err: ' + err);
                var emptyItem = {
                    title: "欢迎光临本站",
                    content: "还没有文章",
                    publish: Date.now() - 61,
                    link: '#',
                }
                dataset.push(emptyItem);
            }
            logger.debug(dataset);

            BookMark.all(function(marks, err) {
                if (err) {
                    logger.error(errStr);
                }
                res.render('index', {
                    user: req.user,
                    articles: dataset,
                    bookMarks: marks,
                    imgs: imageList,
                });

            });
            // update new data
            updateNewBlog(dataset);
            // delete old data
            deleteOldBlog(dataset);
        });
    });
};

function updateNewBlog(dataset) {
    var timeInterval = Date.now() - dataset[0].publish;
    logger.debug(timeInterval);
    if (dataset.length == 1 || timeInterval > 1000 * 60 * 60 * 24 * 2) {
        rssService.getBlogs(function(rssResults, err) {
            //logger.debug(rssResults);
            Article.saveAll(rssResults, function(err) {
                if (err) {
                    logger.error('Open index then save all articles err: ' + err);
                }
            });
        });
    };
};

function deleteOldBlog(dataset) {
    if (dataset.length != 1) {
        earlyDate = dataset[dataset.length - 1].publish;
        Article.deleteOld(earlyDate, function(err) {
            if (err) {
                logger.error('Open index then delete older articles err: ' + err);
            }
        })
    };
}

function updateImage() {
    var needUpadte = false;
    imageList.forEach(function(imagePath, i) {
        imagePath = 'public/' + imagePath;
        fs.stat(imagePath, function(err, stat) {
            if (err) {
                needUpadte = true;
                logger.debug("文件不存在！" + err);
            } else {
                logger.debug("是否文件：" + stat.isFile());
                logger.debug("是否文件夹：" + stat.isDirectory());
                var timeInterval = Date.now() - stat.mtime;
                if (timeInterval > 1000 * 60 * 60 * 24) {
                    needUpadte = true;
                    logger.debug(imagePath + " 需要更新");
                }
            }
            if (needUpadte) {
                logger.info("下载：" + imagePath);
                imageService.downloadImg(imagePath);
            }
        });
    });
}


exports.search = function(req, res) {
    res.render('search', {user: req.user});
}